<template>
  <div class="pdccontent-box">
    <pdc-nav-bar @publicdynamic="publicdynamic" />
    <div class="dynamic-text">
      <van-field
        v-model="message"
        rows="2"
        autosize
        type="textarea"
        maxlength="50"
        placeholder="分享新鲜事..."
        show-word-limit
      />
    </div>
    <div class="dynamic-img">
      <van-uploader v-model="fileList" multiple :max-count="9" :after-read="afterRead" />
    </div>
  </div>
</template>

<script>
import PdcNavBar from "./pdcchildcomps/PdcNavBar";

import { getUrlBase642 } from "common/utils";
import { mapState } from "vuex";

import { publicTextDynamic } from "network/dynamic";
import { uploadingHousePicture } from "network/uploadImg";

export default {
  name: "publicdynamiccontent",
  components: {
    PdcNavBar,
  },
  data() {
    return {
      message: "",
      fileList: [],
      imageList: [],
    };
  },
  methods: {
    toBack() {
      this.$router.back();
    },
    publicdynamic() {
      let userId = this.userId;
      let context = this.message;
      let imageList = this.imageList;
      if (!context) {
        this.$toast({
          message: "发表内容不能为空",
          position: "bottom",
        });
        return;
      }
      publicTextDynamic({ userId, context, imageList }).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.$toast({
            message: "发布成功",
            position: "bottom",
          });
          this.$router.replace("/friendcircle");
          // this.$router.go(0)
          this.message = "";
          this.fileList = [];
          this.imageList = [];
        }
      });
    },
    //上传图片
    afterRead(file) {
      if (file.length > 1) {
        //使用for循环来适配多选情况
        for (let i in file) {
          this.upimg(file[i]);
        }
      } else {
        this.upimg(file);
      }
    },
    //上传图片到服务器
    upimg(e) {
      if (e.file.size / 1024 / 1024 > 5) {
        this.$toast({
          message: "图片不能超过5M",
          position: "bottom",
        });
        return;
      }
      var formdata = new FormData();
      formdata.append("files", e.file);
      uploadingHousePicture(formdata).then((res) => {
        console.log(res);
        this.imageList.push(res.data[0]);
      });
    },
  },
  computed: {
    ...mapState({
      userId: (state) => state.moduleUser.userId,
    }),
  },
};
</script>

<style scoped>
.pdccontent-box {
  padding-top: 50px;
  height: 100vh;
  background-color: #efefef;
}
.dynamic-text {
  margin: 15px;
  border-radius: 10px;
  overflow: hidden;
}
.dynamic-img {
  margin: 15px;
  border-radius: 10px;
  padding: 15px 30px;
  background-color: #fff;
}
</style>